#
# mydbms/pysql_compiler/parser.py
#

from .lexer import Token
from .ast import (
    SelectStatementNode, BinaryOperationNode, NumberNode,
    StringNode, IdentifierNode, StarNode, InsertStatementNode,
    UpdateStatementNode, DeleteStatementNode, AssignmentNode,
    CreateTableStatementNode, ColumnDefinitionNode, DataTypeNode,
    CreateIndexStatementNode, OrderByNode, FunctionCallNode, AliasNode,
    TruncateTableStatementNode, InPredicateNode, JoinNode,
    # <<<--- 导入约束节点 (主键约束等) ---<<<
    PrimaryKeyConstraintNode, AutoIncrementConstraintNode, NotNullConstraintNode,
    UniqueConstraintNode, CheckConstraintNode, DropTableStatementNode,
    # 导入ALTER的相关节点
    AlterTableStatementNode, AddColumnNode, AlterColumnNode, DropColumnNode, AddPrimaryKeyNode,
    UnaryOperationNode, LikePredicateNode, IsNullPredicateNode, DropIndexStatementNode,
    ShowTablesStatementNode,
    ExplainStatementNode,
    ForeignKeyConstraintNode, BooleanLiteralNode
)


class Parser:
    """SQL语法分析器，将Token流转换为AST"""

    def __init__(self, tokens: list[Token]):
        self.tokens = tokens
        self.pos = 0

    def _current_token(self):
        """返回当前位置的Token，如果越界则返回None"""
        return self.tokens[self.pos] if self.pos < len(self.tokens) else None

    def _advance(self):
        """将指针向前移动一位"""
        self.pos += 1

    def _eat(self, expected_type: str):
        """
        消耗一个Token。如果当前Token类型与预期相符，则前进；否则抛出异常。
        """
        current = self._current_token()
        if current and current.type == expected_type:
            self._advance()
            return current
        else:
            expected = f"'{expected_type}'" if current else "more tokens"
            found = f"'{current.type}'" if current else "end of input"
            location = f" at line {current.line} column {current.col}" if current else ""
            raise ValueError(f"Syntax Error: Expected {expected}, but found {found}{location}")

    def _raise_syntax_error(self, expected: str, found: Token):
        """一个辅助函数，用于抛出统一格式的语法错误。"""
        found_str = f"'{found.value}' ({found.type})" if found else "end of input"
        location = f" at line {found.line} column {found.col}" if found else ""
        raise ValueError(f"Syntax Error: Expected {expected}, but found {found_str}{location}")

    def parse(self):
        """解析主入口"""
        if not self._current_token():
            raise ValueError("Cannot parse an empty query.")

        token_type = self._current_token().type
        if token_type == 'EXPLAIN':
            self._eat('EXPLAIN')
            explained_statement = self.parse() # 递归调用 parse
            statement = ExplainStatementNode(explained_statement)

        elif token_type == 'SELECT':
            statement = self._parse_select_statement()
        elif token_type == 'INSERT':
            statement = self._parse_insert_statement()
        elif token_type == 'UPDATE':
            statement = self._parse_update_statement()
        elif token_type == 'DELETE':
            statement = self._parse_delete_statement()
        elif token_type == 'CREATE':
            next_token_type = self.tokens[self.pos + 1].type if self.pos + 1 < len(self.tokens) else None

            if next_token_type == 'TABLE':
                statement = self._parse_create_table_statement()
            elif next_token_type == 'INDEX':
                statement = self._parse_create_index_statement()
            else:
                self._eat('CREATE')
                raise ValueError(f"Syntax Error: Expected 'TABLE' or 'INDEX', but found '{next_token_type}'")
        elif token_type == 'TRUNCATE':
            statement = self._parse_truncate_table_statement()
        elif token_type == 'DROP':
            next_token_type = self.tokens[self.pos + 1].type if self.pos + 1 < len(self.tokens) else None
            if next_token_type == 'TABLE':
                statement = self._parse_drop_table_statement()
            elif next_token_type == 'INDEX':
                statement = self._parse_drop_index_statement()
            else:
                self._eat('DROP')
                raise ValueError(f"Syntax Error: Expected 'TABLE' or 'INDEX', but found '{next_token_type}'")
        # 处理ALTER关键字
        elif token_type == 'ALTER':
            statement = self._parse_alter_table_statement()
        elif token_type == 'SHOW':
            statement = self._parse_show_tables_statement()
        else:
            raise ValueError(f"Unsupported statement type: {token_type}")

        current = self._current_token()
        if current and current.type != 'SEMICOLON':
            raise ValueError(f"Syntax Error: Unexpected token '{current.value}' at the end of query.")
        return statement

    def _parse_truncate_table_statement(self) -> TruncateTableStatementNode:
        """解析 TRUNCATE TABLE 语句"""
        self._eat('TRUNCATE')
        self._eat('TABLE')
        table_name = IdentifierNode(self._eat('ID').value)
        return TruncateTableStatementNode(table_name=table_name)

    def _parse_select_statement(self) -> SelectStatementNode:
        """解析 SELECT 语句"""
        self._eat('SELECT')

        is_distinct = False
        if self._current_token() and self._current_token().type == 'DISTINCT':
            self._eat('DISTINCT')
            is_distinct = True

        columns = self._parse_columns()
        from_clause = self._parse_from_clause()

        where_clause = None
        if self._current_token() and self._current_token().type == 'WHERE':
            where_clause = self._parse_where_clause()

        group_by_clause = None
        if self._current_token() and self._current_token().type == 'GROUP':
            group_by_clause = self._parse_group_by_clause()

        having_clause = None
        if self._current_token() and self._current_token().type == 'HAVING':
            having_clause = self._parse_having_clause()

        order_by_clause = None
        if self._current_token() and self._current_token().type == 'ORDER':
            order_by_clause = self._parse_order_by_clause()

        return SelectStatementNode(columns=columns, from_clause=from_clause, where_clause=where_clause,
                                   distinct=is_distinct, order_by_clause=order_by_clause,
                                   group_by_clause=group_by_clause, having_clause=having_clause)

    def _parse_from_clause(self):
        """解析 FROM 子句，支持 JOIN"""
        self._eat('FROM')
        node = self._parse_term() 

        
        while self._current_token() and self._current_token().type in ['JOIN', 'INNER', 'LEFT', 'RIGHT']:
            
            
            # 检查 JOIN 类型 (INNER, LEFT, RIGHT)
            if self._current_token().type in ['INNER', 'LEFT', 'RIGHT']:
                join_type = self._eat(self._current_token().type).value
                # 在 INNER/LEFT/RIGHT 之后，必须紧跟着 JOIN 关键字
                self._eat('JOIN')
            else:
                # 如果直接就是 JOIN 关键字，那么类型就是 INNER
                self._eat('JOIN')
                join_type = 'INNER'


            right_table = self._parse_term() # 解析 JOIN 后面的表名, e.g., courses
            self._eat('ON')
            condition = self._parse_where_clause_condition()
            node = JoinNode(left=node, right=right_table, join_type=join_type.upper(), condition=condition)

        return node

    def _parse_order_by_clause(self) -> OrderByNode:
        """解析 ORDER BY 子句"""
        self._eat('ORDER')
        self._eat('BY')
        column = self._parse_term()

        order = 'ASC'
        if self._current_token():
            if self._current_token().type == 'ASC':
                self._eat('ASC')
                order = 'ASC'
            elif self._current_token().type == 'DESC':
                self._eat('DESC')
                order = 'DESC'

        return OrderByNode(column=column, order=order)

    def _parse_group_by_clause(self) -> list[IdentifierNode]:
        """解析 GROUP BY 子句"""
        self._eat('GROUP')
        self._eat('BY')
        return self._parse_identifier_list()

    def _parse_having_clause(self) -> BinaryOperationNode:
        """解析 HAVING 子句 (简化版，结构同 WHERE)"""
        self._eat('HAVING')
        return self._parse_where_clause_condition()

    def _parse_insert_statement(self) -> InsertStatementNode:
        """解析 INSERT 语句"""
        self._eat('INSERT')
        self._eat('INTO')
        table = self._parse_term()

        columns = []
        if self._current_token() and self._current_token().type == 'LPAREN':
            self._eat('LPAREN')
            columns = self._parse_identifier_list()
            self._eat('RPAREN')

        self._eat('VALUES')

        values_list = []
        while True:
            self._eat('LPAREN')
            values_list.append(self._parse_value_list())
            self._eat('RPAREN')
            if self._current_token() and self._current_token().type == 'COMMA':
                self._advance()
            else:
                break

        return InsertStatementNode(table=table, columns=columns, values=values_list)

    def _parse_update_statement(self) -> UpdateStatementNode:
        """解析 UPDATE 语句"""
        self._eat('UPDATE')
        table = self._parse_term()
        self._eat('SET')
        assignments = self._parse_assignments()

        from_table = None
        if self._current_token() and self._current_token().type == 'FROM':
            self._eat('FROM')
            from_table = self._parse_term()

        where_clause = None
        if self._current_token() and self._current_token().type == 'WHERE':
            where_clause = self._parse_where_clause()

        return UpdateStatementNode(table=table, assignments=assignments, from_table=from_table,
                                   where_clause=where_clause)

    def _parse_delete_statement(self) -> DeleteStatementNode:
        """解析 DELETE 语句"""
        self._eat('DELETE')
        self._eat('FROM')
        table = IdentifierNode(self._eat('ID').value)

        where_clause = None
        if self._current_token() and self._current_token().type == 'WHERE':
            where_clause = self._parse_where_clause()

        return DeleteStatementNode(table=table, where_clause=where_clause)

    def _parse_create_table_statement(self) -> CreateTableStatementNode:
        """解析 CREATE TABLE 语句"""
        self._eat('CREATE')
        self._eat('TABLE')
        table_name = IdentifierNode(self._eat('ID').value)
        self._eat('LPAREN')
        columns = self._parse_column_definitions()
        self._eat('RPAREN')
        return CreateTableStatementNode(table_name=table_name, columns=columns)

    def _parse_create_index_statement(self) -> CreateIndexStatementNode:
        """解析 CREATE INDEX 语句, 格式: CREATE INDEX index_name ON table_name (column_name);"""
        self._eat('CREATE')
        self._eat('INDEX')
        index_name = IdentifierNode(self._eat('ID').value)
        self._eat('ON')
        table_name = IdentifierNode(self._eat('ID').value)
        self._eat('LPAREN')
        column_name = IdentifierNode(self._eat('ID').value)
        self._eat('RPAREN')
        return CreateIndexStatementNode(index_name, table_name, column_name)

    def _parse_single_column_definition(self) -> ColumnDefinitionNode:
        """
        解析单个列定义，专为 ALTER TABLE ADD COLUMN 设计，不处理括号或逗号。
        格式: column_name data_type [constraints...]
        """
        column_name = IdentifierNode(self._eat('ID').value)
        data_type_value = self._eat('ID').value
        if self._current_token() and self._current_token().type == 'LPAREN':
            self._eat('LPAREN')
            data_type_value += f"({self._eat('NUMBER').value})"
            self._eat('RPAREN')
        data_type = DataTypeNode(data_type_value)

        constraints = []
        # 此处可以添加对列约束的解析，如果您的 ALTER 语法支持的话
        # 例如: ALTER TABLE students ADD email VARCHAR NOT NULL;
        # (当前保持简化，与您的测试用例匹配)

        return ColumnDefinitionNode(column_name, data_type, constraints)


    def _parse_column_definitions(self) -> list:
        """
        解析列定义和表约束的列表。
        此版本能正确处理简单的列定义（如 "id INT"）
        以及表级约束（如 "FOREIGN KEY (...)"）。
        """
        definitions = []

        while self._current_token() and self._current_token().type != 'RPAREN':
            token_type = self._current_token().type

            # 可选：处理 CONSTRAINT constraint_name 语法
            if token_type == 'CONSTRAINT':
                self._eat('CONSTRAINT')
                self._eat('ID') # 暂时忽略约束名称
                token_type = self._current_token().type

           
            if token_type == 'ID':
                # 情况 A: 这是一个列定义（以列名开头）
                column_name = IdentifierNode(self._eat('ID').value)
                data_type_value = self._eat('ID').value
                if self._current_token() and self._current_token().type == 'LPAREN':
                    self._eat('LPAREN')
                    data_type_value += f"({self._eat('NUMBER').value})"
                    self._eat('RPAREN')
                data_type = DataTypeNode(data_type_value)

                # 解析该列的任何行内约束（PRIMARY KEY, 等）
                constraints = []
                while self._current_token() and self._current_token().type in ['PRIMARY', 'AUTO_INCREMENT', 'NOT', 'UNIQUE', 'CHECK']:
                    constraint_type = self._current_token().type
                    if constraint_type == 'PRIMARY':
                        self._eat('PRIMARY')
                        self._eat('KEY')
                        constraints.append(PrimaryKeyConstraintNode())
                    elif constraint_type == 'AUTO_INCREMENT':
                        self._eat('AUTO_INCREMENT')
                        constraints.append(AutoIncrementConstraintNode())
                    elif constraint_type == 'NOT':
                        self._eat('NOT')
                        self._eat('NULL')
                        constraints.append(NotNullConstraintNode())
                    elif constraint_type == 'UNIQUE':
                         self._eat('UNIQUE')
                         constraints.append(UniqueConstraintNode())
                    elif constraint_type == 'CHECK':
                        self._eat('CHECK')
                        self._eat('LPAREN')
                        expr = self._parse_where_clause_condition()
                        self._eat('RPAREN')
                        constraints.append(CheckConstraintNode(expr))

                definitions.append(ColumnDefinitionNode(column_name, data_type, constraints))
            
            elif token_type == 'UNIQUE':
                # 情况 B: 这是一个表级 UNIQUE 约束
                self._eat('UNIQUE')
                self._eat('LPAREN')
                columns = self._parse_identifier_list()
                self._eat('RPAREN')
                definitions.append(UniqueConstraintNode(columns))

            elif token_type == 'FOREIGN':
                # 情况 C: 这是一个表级 FOREIGN KEY 约束
                self._eat('FOREIGN')
                self._eat('KEY')
                self._eat('LPAREN')
                column_name = IdentifierNode(self._eat('ID').value)
                self._eat('RPAREN')
                self._eat('REFERENCES')
                ref_table = IdentifierNode(self._eat('ID').value)
                self._eat('LPAREN')
                ref_column = IdentifierNode(self._eat('ID').value)
                self._eat('RPAREN')
                definitions.append(ForeignKeyConstraintNode(column_name, ref_table, ref_column))

            else:
                self._raise_syntax_error(expected="column definition or table constraint", found=self._current_token())
            
            if self._current_token() and self._current_token().type == 'COMMA':
                self._advance()
            elif self._current_token() and self._current_token().type != 'RPAREN':
                self._raise_syntax_error(expected="',' or ')'", found=self._current_token())

        return definitions

    def _parse_columns(self) -> list:
        """解析 SELECT 后的列名列表"""
        if self._current_token().type == 'STAR':
            self._advance()
            return [StarNode()]

        columns = []
        while True:
            expr = self._parse_expression()
            if self._current_token() and self._current_token().type == 'AS':
                self._eat('AS')
                alias = IdentifierNode(self._eat('ID').value)
                expr = AliasNode(expression=expr, alias=alias)
            columns.append(expr)

            if self._current_token() and self._current_token().type == 'COMMA':
                self._advance()
            else:
                break
        return columns

    def _parse_identifier_list(self) -> list:
        """解析逗号分隔的标识符列表"""
        identifiers = []
        while True:
            identifiers.append(self._parse_term())
            if self._current_token() and self._current_token().type == 'COMMA':
                self._advance()
            else:
                break
        return identifiers

    def _parse_value_list(self) -> list:
        """解析逗号分隔的值列表"""
        values = []
        while True:
            values.append(self._parse_term())
            if self._current_token() and self._current_token().type == 'COMMA':
                self._advance()
            else:
                break
        return values

    # --- 新增函数: 用于解析算术表达式 ---
    def _parse_arithmetic_factor(self):
        """解析一个因子，它可以是一个项(如列名、数字)或一个带括号的表达式。"""
        if self._current_token() and self._current_token().type == 'LPAREN':
            self._eat('LPAREN')
            node = self._parse_additive_expression() # 递归调用以处理括号内的表达式
            self._eat('RPAREN')
            return node
        else:
            return self._parse_term()

    def _parse_multiplicative_expression(self):
        """处理乘法 (*) 和除法 (/)，优先级较高。"""
        node = self._parse_arithmetic_factor()
        while self._current_token():
            token = self._current_token()
            op_value = token.value
            if token.type == 'STAR': # 注意：乘法使用 STAR Token
                self._eat('STAR')
                right = self._parse_arithmetic_factor()
                node = BinaryOperationNode(left=node, op='*', right=right)
            elif token.type == 'OP' and op_value == '/':
                self._eat('OP')
                right = self._parse_arithmetic_factor()
                node = BinaryOperationNode(left=node, op='/', right=right)
            else:
                break
        return node

    def _parse_additive_expression(self):
        """处理加法 (+)、减法 (-)和字符串连接 (||)，优先级较低。"""
        node = self._parse_multiplicative_expression()
        while self._current_token() and self._current_token().type == 'OP' and self._current_token().value in ['+', '-','||']:
            op = self._eat('OP').value
            right = self._parse_multiplicative_expression()
            node = BinaryOperationNode(left=node, op=op, right=right)
        return node

    # --- 核心修改: 更新此函数以使用新的表达式解析器 ---
    def _parse_assignments(self) -> list[AssignmentNode]:
        """解析 SET 后面的赋值列表"""
        assignments = []
        while True:
            column = self._parse_term()
            op_token = self._eat('OP')
            if op_token.value != '=':
                raise ValueError(f"Syntax Error: Expected '=' in assignment, but found '{op_token.value}'")

            # 调用新的表达式解析器，而不是原来的 _parse_term()
            value = self._parse_additive_expression()
            assignments.append(AssignmentNode(column, value))

            if self._current_token() and self._current_token().type == 'COMMA':
                self._advance()
            else:
                break
        return assignments

    def _parse_where_clause(self):
        """解析 WHERE 子句的入口"""
        self._eat('WHERE')
        return self._parse_where_clause_condition()

    def _parse_where_clause_condition(self):
        """解析 WHERE 子句的条件 (支持 OR)"""
        node = self._parse_and_condition()
        while self._current_token() and self._current_token().type == 'OR':
            op = self._eat('OR').value
            right = self._parse_and_condition()
            node = BinaryOperationNode(left=node, op=op, right=right)
        return node

    def _parse_and_condition(self):
        """解析 AND 连接的条件"""
        node = self._parse_not_condition()
        while self._current_token() and self._current_token().type == 'AND':
            op = self._eat('AND').value
            right = self._parse_not_condition()
            node = BinaryOperationNode(left=node, op=op, right=right)
        return node

    def _parse_not_condition(self):
        """解析 NOT 条件"""
        if self._current_token() and self._current_token().type == 'NOT':
            op = self._eat('NOT').value
            operand = self._parse_not_condition()
            return UnaryOperationNode(op=op, operand=operand)

        # --- 核心修改 ---
        # 在解析基本比较条件之前，检查是否存在由括号包裹的复杂条件。
        # 这使得解析器能够处理像 (A AND B) OR C 这样的逻辑分组。
        if self._current_token() and self._current_token().type == 'LPAREN':
            self._eat('LPAREN')
            # 如果遇到左括号，就递归调用顶层的条件解析函数
            # 来解析括号内的完整逻辑表达式。
            node = self._parse_where_clause_condition()
            self._eat('RPAREN')
            return node
        else:
            # 如果没有括号，则按原计划解析一个基本的比较表达式 (e.g., age > 20)。
            return self._parse_comparison()

    def _parse_comparison(self):
        """解析比较、LIKE、IN、IS NULL 等基本条件"""
        left = self._parse_term()

        if self._current_token():
            if self._current_token().type == 'IN':
                self._eat('IN')
                self._eat('LPAREN')
                if self._current_token().type == 'SELECT':
                    subquery = self._parse_select_statement()
                    self._eat('RPAREN')
                    return InPredicateNode(identifier=left, subquery=subquery)
                else:
                    values = self._parse_value_list()
                    self._eat('RPAREN')
                    return InPredicateNode(identifier=left, subquery=values)

            elif self._current_token().type == 'LIKE':
                self._eat('LIKE')
                pattern = self._parse_term()
                return LikePredicateNode(left=left, pattern=pattern)

            elif self._current_token().type == 'IS':
                self._eat('IS')
                is_not = False
                if self._current_token() and self._current_token().type == 'NOT':
                    self._eat('NOT')
                    is_not = True
                self._eat('NULL')
                return IsNullPredicateNode(left=left, is_not=is_not)

            elif self._current_token().type == 'OP':
                op = self._eat('OP').value
                right = self._parse_term()
                return BinaryOperationNode(left=left, op=op, right=right)

        return left

    def _parse_expression(self):
        """解析表达式，可以是标识符、函数调用等"""
        token = self._current_token()

        is_function_call = False
        if token.type in ['ID', 'COUNT', 'SUM', 'AVG', 'MAX', 'MIN']:
            next_token = self.tokens[self.pos + 1] if self.pos + 1 < len(self.tokens) else None
            if next_token and next_token.type == 'LPAREN':
                is_function_call = True

        if is_function_call:
            func_name = self._current_token().value
            self._advance()

            self._eat('LPAREN')
            args = []
            if self._current_token().type != 'RPAREN':
                if self._current_token().type == 'STAR':
                    args.append(StarNode())
                    self._advance()
                else:
                    args.append(self._parse_expression())
            self._eat('RPAREN')
            return FunctionCallNode(func_name=func_name, args=args)
        else:
            return self._parse_term()

    def _parse_term(self):
        """解析表达式中的项，可以是标识符、数字或字符串 (支持 table.column)"""
        token = self._current_token()
        if not token:
            raise ValueError("Syntax Error: Unexpected end of input in expression")

        if token.type == 'TRUE':
            self._advance()
            return BooleanLiteralNode(True)
        elif token.type == 'FALSE':
            self._advance()
            return BooleanLiteralNode(False)
            # 检查是否为一元负号
        if token.type == 'OP' and token.value == '-':
                self._advance()  # "吃掉" '-' 符号
                next_token = self._current_token()

                if next_token and next_token.type == 'NUMBER':
                    self._advance()  # "吃掉" 数字符号
                    # 构造一个负数
                    value_str = '-' + next_token.value
                    # 返回一个 NumberNode, 节点内部处理 int 或 float 转换
                    return NumberNode(float(value_str) if '.' in value_str else int(value_str))
                else:
                    # 如果 '-' 后面不是数字, 这是一个语法错误
                    raise ValueError(
                        f"Syntax Error: Unexpected token after unary minus: {next_token.value if next_token else 'EOF'}")
            # --- 新增代码结束 ---

        if token.type == 'ID':
            value = self._eat('ID').value
            if self._current_token() and self._current_token().type == 'DOT':
                self._eat('DOT')
                value += '.' + self._eat('ID').value
            return IdentifierNode(value)
        elif token.type == 'NUMBER':
            self._advance()
            return NumberNode(float(token.value) if '.' in token.value else int(token.value))
        elif token.type == 'STRING':
            self._advance()
            return StringNode(token.value[1:-1])
        else:
            raise ValueError(f"Syntax Error: Unexpected term in expression: {token.value}")

    def _parse_drop_table_statement(self) -> DropTableStatementNode:
        """解析 DROP TABLE 语句"""
        self._eat('DROP')
        self._eat('TABLE')
        table_name = IdentifierNode(self._eat('ID').value)
        return DropTableStatementNode(table_name=table_name)

    def _parse_alter_table_statement(self) -> AlterTableStatementNode:
        """解析ALTER TABLE语句"""
        self._eat('ALTER')
        self._eat('TABLE')
        table_name = IdentifierNode(self._eat('ID').value)

        action_token = self._current_token()
        if action_token.type == 'ADD':
            self._eat('ADD')
            if self._current_token().type == 'PRIMARY':
                self._eat('PRIMARY')
                self._eat('KEY')
                self._eat('LPAREN')
                column_name = IdentifierNode(self._eat('ID').value)
                self._eat('RPAREN')
                action = AddPrimaryKeyNode(column_name)
            else:
                # *** 核心修正 ***
                # 调用专用的单个列定义解析方法
                column_def = self._parse_single_column_definition()
                action = AddColumnNode(column_def)

        elif action_token.type == 'ALTER':
            self._eat('ALTER')
            self._eat('COLUMN')
            column_name = IdentifierNode(self._eat('ID').value)
            new_data_type = DataTypeNode(self._eat('ID').value)
            action = AlterColumnNode(column_name, new_data_type)

        elif action_token.type == 'DROP':
            self._eat('DROP')
            self._eat('COLUMN')
            column_name = IdentifierNode(self._eat('ID').value)
            action = DropColumnNode(column_name)

        else:
            raise ValueError(f"Unsupported ALTER TABLE action: {action_token.type}")

        return AlterTableStatementNode(table_name, action)

    def _parse_drop_index_statement(self) -> DropIndexStatementNode:
        """解析 DROP INDEX 语句"""
        self._eat('DROP')
        self._eat('INDEX')
        index_name = IdentifierNode(self._eat('ID').value)
        return DropIndexStatementNode(index_name=index_name)

    def _parse_show_tables_statement(self) -> ShowTablesStatementNode:
        """解析 SHOW TABLES 语句"""
        self._eat('SHOW')
        self._eat('TABLES')
        return ShowTablesStatementNode()
